import UIKit
import GradientLoadingBar
import SwiftEventBus
import SwiftyStoreKit


class VipViewController: UIViewController{
    let scrollView = UIScrollView()
    var containerView: UIView!
    let cell_identifier:String = "vipCell"
    
    lazy var tableView : UICollectionView = {
        
        let layout = UICollectionViewFlowLayout()
        
        let itemW = (UIScreen.main.bounds.width - 40)/3
        layout.itemSize = CGSize(width: itemW, height: itemW + 24)
        
        layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
        layout.minimumLineSpacing = 12
        layout.minimumInteritemSpacing = 10
        
        layout.scrollDirection = .horizontal // 竖向滑动
        
        let tableView = UICollectionView(frame: CGRectMake(0, 0, UIScreen.main.bounds.width, UIScreen.main.bounds.height-48), collectionViewLayout: layout)
        tableView.showsVerticalScrollIndicator = false
        tableView.delegate = self
        tableView.dataSource = self
        tableView.showsHorizontalScrollIndicator = false
        tableView.backgroundColor = UIColor("#1f1347")
        tableView.register(VipCell.self, forCellWithReuseIdentifier: cell_identifier)
        
        return tableView
    }()
    
    override func viewDidDisappear(_ animated: Bool) {
        ProgressHUD.dismiss()
    }
    override var wx_titleTextAttributes: [NSAttributedString.Key : Any]? {
        return [NSAttributedString.Key.foregroundColor: UIColor.white]
    }
    private let gradientLoadingBar = NotchGradientLoadingBar(
        height: 3.0
    )
    var fromPage: String?
    override func viewDidLoad() {
        
        
        
        
        self.view.backgroundColor = UIColor("#1f1347")
        view.addSubview(scrollView)
        scrollView.showsVerticalScrollIndicator = false
        scrollView.snp.makeConstraints { (make) in
            make.left.top.right.equalToSuperview()
            make.bottom.equalTo(self.view.safeAreaLayoutGuide.snp.bottom)
        }
        containerView = UIView()
        scrollView.addSubview(containerView)
        containerView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
            make.width.equalTo(UIScreen.main.bounds.width)
        }
        
        let vipImageView = UIImageView(image: UIImage(named: "vip"))
        containerView.addSubview(vipImageView)
        vipImageView.snp.makeConstraints { make in
            make.top.equalTo(containerView.safeAreaLayoutGuide.snp.top)
            make.centerX.equalTo(containerView)
        }
        
        containerView.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(vipImageView.snp.bottom).offset(24)
            make.width.equalTo(UIScreen.main.bounds.width)
            make.height.equalTo(160)
        }
        
        let autoLabel = UILabel()
        autoLabel.text = "自动续费，可随时取消"
        autoLabel.textColor = .white.withAlphaComponent(0.3)
        autoLabel .font = UIFont.systemFont(ofSize: 11)
        containerView.addSubview(autoLabel)
        
        autoLabel.snp.makeConstraints { make in
            make.centerX.equalTo(containerView)
            make.bottom.equalTo(tableView.snp.bottom).offset(12)
        }
        
        let purchaseButton = UIButton(type: .custom)

        
        let gradientLayer = CAGradientLayer()
        gradientLayer.frame = CGRectMake(0, 0, UIScreen.main.bounds.width - 24, 48)
        gradientLayer.colors = [UIColor("#3124ad").cgColor, UIColor("#c56bd6").cgColor]
        gradientLayer.startPoint = CGPoint(x: 0, y: 0.5)
        gradientLayer.endPoint = CGPoint(x: 1, y: 0.5)
        gradientLayer.cornerRadius = 24
        purchaseButton.layer.addSublayer(gradientLayer)
       
        purchaseButton.setTitle("立即开通", for: .normal)
        
        purchaseButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: .semibold)

        purchaseButton.addTarget(self, action: #selector(purchase(_:)), for: .touchUpInside)
        
        containerView.addSubview(purchaseButton)
        purchaseButton.snp.makeConstraints { make in
            make.centerX.equalTo(containerView)
            make.top.equalTo(tableView.snp.bottom).offset(24)
            make.height.equalTo(48)
            make.width.equalTo(UIScreen.main.bounds.width - 24)
        }
        
        
        
        let yisiButton = UIButton(type: .custom)
        yisiButton.setTitle("隐私政策", for: .normal)
        yisiButton.layer.cornerRadius = 12
        yisiButton.setTitleColor(.white, for: .normal)
        yisiButton.titleLabel?.font = UIFont.systemFont(ofSize: 12, weight: .semibold)
       
        yisiButton.isUserInteractionEnabled = true
        yisiButton.addTarget(self, action: #selector(yisi(_:)), for: .touchUpInside)
        containerView.addSubview(yisiButton)
        yisiButton.snp.makeConstraints({ make in
            make.top.equalTo(purchaseButton.snp.bottom)
            make.centerX.equalTo(containerView)
            make.width.equalTo(62)
            make.height.equalTo(32)
        })
        
        
        let fuwuButton = UIButton(type: .custom)
        fuwuButton.setTitle("服务条款", for: .normal)
        fuwuButton.layer.cornerRadius = 12
        fuwuButton.setTitleColor(.white, for: .normal)
        fuwuButton.titleLabel?.font = UIFont.systemFont(ofSize: 12, weight: .semibold)
       
        fuwuButton.isUserInteractionEnabled = true
        fuwuButton.addTarget(self, action: #selector(fuwu(_:)), for: .touchUpInside)
        containerView.addSubview(fuwuButton)
        fuwuButton.snp.makeConstraints({ make in
            make.top.equalTo(purchaseButton.snp.bottom)
            make.right.equalTo(yisiButton.snp.left).offset(-8)
            make.width.equalTo(62)
            make.height.equalTo(32)
        })
        
        
        let restoreButton = UIButton(type: .custom)
        restoreButton.setTitle("恢复购买", for: .normal)
        restoreButton.layer.cornerRadius = 12
        restoreButton.setTitleColor(.white, for: .normal)
        restoreButton.titleLabel?.font = UIFont.systemFont(ofSize: 12, weight: .semibold)
       
        restoreButton.isUserInteractionEnabled = true
        restoreButton.addTarget(self, action: #selector(restore(_:)), for: .touchUpInside)
        containerView.addSubview(restoreButton)
        restoreButton.snp.makeConstraints({ make in
            make.top.equalTo(purchaseButton.snp.bottom)
            make.left.equalTo(yisiButton.snp.right).offset(8)
            make.width.equalTo(62)
            make.height.equalTo(32)
        })
        
        
        
        let tip = UILabel()
        tip.textColor = .white.withAlphaComponent(0.3)
        tip.numberOfLines = 0
        tip .font = UIFont.systemFont(ofSize: 11)
        tip.lineBreakMode = .byWordWrapping
        tip.text = "您可通过前往iTunes账号设置并取消订阅的方式,必须在当前有效期结束前至少24小时禁用，否则将自动续费.我们将在当前有效期结束前24小时内向您的账号收取续订费用,订阅款项将从您的iTunes账户中扣除. 请注意：试用期（如果提供）的任何未使用部分将在用户购买该出版物的订阅时（如果适用）失效。了解更多信息,请参阅我们的"
        self.view.addSubview(tip)
        tip.snp.makeConstraints { make in
            make.left.equalTo(containerView).offset(12)
            make.right.equalTo(containerView).offset(-12)
            make.top.equalTo(restoreButton.snp.bottom).offset(16)
        }
        
        containerView.snp.makeConstraints({ (make) in
            make.bottom.equalTo(tip.snp.bottom)
            
        })
        
        initProduct()
        
        PurchaseManager.sharedInstance.addFromPage(fromPage)
        
        PurchaseManager.sharedInstance.addCompleteHandler{
            state in
            
            switch state{
            case .purchasing:
                ProgressHUD.show("请稍后...")
            case .purchased:
                ProgressHUD.showSucceed()
                StoreManager.setVip(vip: true)
                SwiftEventBus.post(EVENT_NAME_REFRESH_VIP_STATE)
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1){
                    self.navigationController?.popViewController(animated: true)
                }
            case .restored:
                ProgressHUD.showSucceed()
                StoreManager.setVip(vip: true)
                SwiftEventBus.post(EVENT_NAME_REFRESH_VIP_STATE)
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1){
                    self.navigationController?.popViewController(animated: true)
                }
                
            case .failed, .deferred:
                print("failllllllllllll")
                ProgressHUD.showFailed()
                
                
            default:
                ProgressHUD.dismiss()
                print("deffffffffffffff")
            }
            
        }
    }
    
    
    func initProduct(){
        if PurchaseManager.sharedInstance.productList.isEmpty{
            ProgressHUD.show("正在获取商品列表，请稍后")
            PurchaseManager.sharedInstance.getChatGptProducts()
        }
       
        SwiftEventBus.onMainThread(self, name: EVENT_NAME_PRODUCT_LOAD) { result in
            ProgressHUD.dismiss()
            self.tableView.reloadData()
        }
        
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2){
            self.tableView.reloadData()
        }
    }

    @objc private func yisi(_ sender: Any) {
        
        tapYinsi()
    }
    
    @objc private func fuwu(_ sender: Any) {
        
        tapYinsi()
    }
    
    func tapYinsi() {
        let urlString = "https://docs.qq.com/doc/DZVZubHhRZWlwbXJM"
        if let url = URL(string: urlString) {
            //根据iOS系统版本，分别处理
            if #available(iOS 10, *) {
                UIApplication.shared.open(url, options: [:],
                                          completionHandler: {
                    (success) in
                })
            } else {
                UIApplication.shared.openURL(url)
            }
        }
    }
    
    @objc private func restore(_ sender: Any) {
        
        ProgressHUD.show()
        SwiftyStoreKit.restorePurchases(atomically: true) { results in
            ProgressHUD.dismiss()
            if results.restoreFailedPurchases.count > 0 {
                self.view.makeToast("恢复购买失败",position: .center)
            }
            else if results.restoredPurchases.count > 0 {
                self.view.makeToast("恢复购买成功",position: .center)
               
                StoreManager.setVip(vip: true)
               
                self.navigationController?.popViewController(animated: true)
            }
            else {
                print("Nothing to Restore")
            }
        }
    }
    
    @objc private func purchase(_ sender: Any) {
        ProgressHUD.show("请稍后...")
        for index in 0..<PurchaseManager.sharedInstance.productList.count {
            if index == 0 , PurchaseManager.sharedInstance.productList[index].isSelect{
                PurchaseManager.sharedInstance.weekPurchase()
            }else if index == 1, PurchaseManager.sharedInstance.productList[index].isSelect{
                PurchaseManager.sharedInstance.yearPurchase()
            }else if PurchaseManager.sharedInstance.productList[index].isSelect{
                PurchaseManager.sharedInstance.monthPurchase()
            }
        }
        
    }
}
extension VipViewController: UICollectionViewDataSource,UICollectionViewDelegate{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return PurchaseManager.sharedInstance.productList.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cell_identifier, for: indexPath) as! VipCell
        cell.bindViewModel(product:PurchaseManager.sharedInstance.productList[indexPath.row],indexPath.row)
        return cell
        
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        self.refreshItem(indexPath.row)
        
    }
    
    func refreshItem(_ selectIndex: Int){
        for index in 0..<PurchaseManager.sharedInstance.productList.count {
            if index == selectIndex{
                PurchaseManager.sharedInstance.productList[index].isSelect = true
            }else{
                PurchaseManager.sharedInstance.productList[index].isSelect = false
            }
        }
        self.tableView.reloadData()
    }
    
}
